package com.swust.excel.read.onesheet;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ReadOneListener extends AnalysisEventListener<ReadOneBean> {

    /**
     * 每隔1000条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    List<ReadOneBean> list = new ArrayList<>();

    @Override
    public void invoke(ReadOneBean read1Bean, AnalysisContext analysisContext) {
        list.add(read1Bean);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            // 模拟存储数据
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        if (list.size() < BATCH_COUNT) {
            saveData();
        }
    }

    private void saveData() {
        System.out.println(list);
    }
}
